﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MvcEngine.Core;

using MvcEngine.Core.Repositories;
using MvcEngine.Mvc.Models.ViewModels;
using MvcEngine.Mvc.Filters;
using MvcEngine.Core.Services;
using MvcEngine.Core.Helpers;
using MvcEngine.Core.Content;
using MvcEngine.Mvc.Controllers;
using MvcEngine.Mvc.Models;

namespace MvcEngine.Mvc.BackOffice.Controllers
{
    public class HomeController : BaseController
    {
        public MvcEngineModel Index()
        {
            return new MvcEngineModel() { ViewName = "Index" };
        }

        [ValidateInput(false)]
        public MvcEngineModel Menu()
        {
            List<MenuViewModel> model = new List<MenuViewModel>();
            var modules = ContentManager.Current.GetModules();
            foreach (var item in modules)
            {
                if (item.ShowInBackOfficeMenu)
                {
                    var control = ContentManager.Current.GetControls(item.Id).SingleOrDefault(c => !c.Visible);

                    var list = ContentManager.Current.GetPageContentsByControl(control.Id);
                    if (list.Count > 0)
                    {
                        if (control != null)
                        {
                            var command = CommandRegistrator.Current.GetCommand(control.Id, "List");
                            if (command != null)
                            {
                                model.Add(new MenuViewModel()
                                {
                                    Title = item.Description,
                                    Url = command.GetUrl(this.ControllerContext.RequestContext)
                                });
                            }
                        }
                    }
                }
            }

            return new MvcEngineModelList<MenuViewModel>() { ViewName = "Menu", List = model };
        }

        public ActionResult Command(int ctrId, string name)
        {
            var pageContent = ContentManager.Current.GetPageContent(ctrId);

            var command = CommandRegistrator.Current.GetCommand(pageContent.ControlId, name);

            if (command == null)
            {
                throw new ArgumentException(string.Format("Command '{0}' was not found in control with id='{1}'", name, pageContent.ControlId));
            }
            return Redirect(command.GetUrl(this.ControllerContext.RequestContext));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult RestartApplication()
        {
            HttpRuntime.UnloadAppDomain();
            return Json(1);
        }
    }
}
